package cn.sumpu.app.wlcity.web.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

public class MonitoredCommonsMultipartResolver extends CommonsMultipartResolver {

	@SuppressWarnings("unchecked")
	public MultipartHttpServletRequest resolveMultipart(
			HttpServletRequest request) throws MultipartException {
		String encoding = determineEncoding(request);
		FileUpload fileUpload = prepareFileUpload(encoding);
		ProgressListener pListener = new DefaultProgressListener(request);
		fileUpload.setProgressListener(pListener);
		try {
			List<FileItem> fileItems = ((ServletFileUpload) fileUpload)
					.parseRequest(request);
			MultipartParsingResult parsingResult = parseFileItems(fileItems,
					encoding);
			return new DefaultMultipartHttpServletRequest(request,
					parsingResult.getMultipartFiles(),
					parsingResult.getMultipartParameters());
		} catch (FileUploadBase.SizeLimitExceededException ex) {
			throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(),
					ex);
		} catch (FileUploadException ex) {
			throw new MultipartException(
					"Could not parse multipart servlet request", ex);
		}
	}

}

class DefaultProgressListener implements ProgressListener {

	private static final Logger logger = LoggerFactory
			.getLogger(DefaultProgressListener.class);

	private HttpSession session = null;

	public DefaultProgressListener() {
	}

	public DefaultProgressListener(HttpServletRequest request) {
		this.session = request.getSession(false);
		if (null != session) {
			session.setAttribute(Constants.MULTIPART_FILE_STATUS,
					new MultipartFileStatus());
		}
	}

	public void update(long bytesRead, long contentLength, int items) {
		if (logger.isDebugEnabled()) {
			logger.debug("bytesRead=" + bytesRead + ",contentLength="
					+ contentLength + ",items=" + items);
		}
		MultipartFileStatus mfs = null;
		if (null != session) {
			mfs = (MultipartFileStatus) session
					.getAttribute(Constants.MULTIPART_FILE_STATUS);
		}
		if (null != mfs) {
			mfs.setStatus(bytesRead, contentLength, items);
		}
	}

}
